import fitz
import sys
from PIL import Image
from webptools import cwebp
import os
from catalog_book import CatalogBook 


 # 把图片转为 webp格式
def convert_to_webp(image_path,webp_path):
    # 打开原始图像文件
    image = Image.open(image_path)
    
    # 获取图像文件名及其路径
    file_name, ext = os.path.splitext(os.path.basename(image_path))
    
    # 构建新的WebP图像文件名
    webp_file_name = f"{file_name}.webp"
    
    try:
        # 将图像保存为WebP格式
        image.save(webp_path +'\\' + webp_file_name, "WEBP")
        
        print(f"成功将 {image_path} 转换为 WebP 格式！输出文件位于 output/{webp_file_name}")
    except Exception as e:
        print(f"无法将 {image_path} 转换为 WebP 格式：{e}")
 
#检查目录是否存在 
def ensure_directory_exists(directory):
    if not os.path.exists(directory):
        os.makedirs(directory)

def init_page_file_name(book):
    print("-----------------init_page_file_name-----------------")
    directory = book.png_path
    file_names = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
   
    page_name = []
    for file_name in file_names:       
        page_name.append(book.png_path+'/'+file_name)

    # 设置页数
    print("共有:"+str(len(file_names))+" png页面带转换!")
    book.pageCount = len(file_names)
    book.page_file=page_name

def book_page_png_2_webp(book):
    for png in book.page_file:
        convert_to_webp(png,book.webp_path)
    
def main():   
    data = queryBook(sys.argv[1])[0]
    # print(data)
    book = CatalogBook(bookId=data[0],title=data[1],filePath=data[2],cover=data[3],pageCount=data[4],shelfId=data[5])
    # print(book)
    # 打印传递给脚本的参数
    # def_pnf_path  = r'D:\Users\65720\Desktop\电信项目-方案\文艺\product-2\1987001\image'
    # def_webp_path = r'D:\Users\65720\Desktop\电信项目-方案\文艺\product-2\1987001\webp'
    def_pnf_path = r'/home/catalog/uploadPath/upload'+ book.cover[:book.cover.rfind('/')]
    def_webp_path = r'/home/catalog/uploadPath/upload'+ book.cover[:book.cover.rfind('/image')]
    book.png_path = sys.argv[2] if len(sys.argv) > 2 else def_pnf_path
    book.webp_path = sys.argv[3] if len(sys.argv) > 3 else def_webp_path
    # print(book)
    #获取png
    init_page_file_name(book)

    #创建输出目录
    ensure_directory_exists(book.webp_path)

    # 调用函数进行转换
    book_page_png_2_webp(book)


from db_connector import connector
def queryBook(book_id):
    sql = f"SELECT * FROM catalog_book WHERE book_id = '{book_id}'"
    result = connector.execute_query(sql)
    return result

if __name__ == "__main__":
    main()
